package 力扣日常刷题.木23一月.第06天306;

/**
 * @author 帅小伙
 * @date 2022/3/6
 * @description
 */
public class Demo55移除无效的括号 {


    public String minRemoveToMakeValid(String s) {
        // 先去多余的左括号
        StringBuilder result = removeInvalidClosing(s, '(', ')');
        // 再去多余的右括号
        result = removeInvalidClosing(result.reverse(), ')', '(');
        return result.reverse().toString();
    }

    public StringBuilder removeInvalidClosing(CharSequence s, char open, char close) {
        StringBuilder sb = new StringBuilder();

        int balance = 0;

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == open) {
                balance++;
            } else if (c == close) {
                if (balance == 0) continue;
                balance--;
            }
            sb.append(c);
        }
        return sb;

    }


}
